package com.boil.qz.safekavass.shiro.filter;

import com.boil.qz.safekavass.model.LoginUser;
import com.boil.util.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.OncePerRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * Created by ChenYong on 2017-04-14.
 * <br>
 * 菜单激活过滤器。
 */
public class MenuActiveFilter extends OncePerRequestFilter {
    /**
     * 日志
     */
    private static Logger log = LoggerFactory.getLogger(MenuActiveFilter.class);

    @Override
    protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 获取请求
        HttpServletRequest request1 = (HttpServletRequest) request;
        // 请求路径
        String servletPath = (StringUtils.isBlank(request1.getServletPath()) ? Constants.EMPTY_STR : request1.getServletPath());
        // 获取登录用户的操作信息
        Subject subject = SecurityUtils.getSubject();

        // 如果已经登录，并且是普通请求
        if (subject.isAuthenticated() && //
                !Constants.AJAX_REQUEST.equalsIgnoreCase(request1.getHeader(Constants.REQUEST_TYPE)) && //
                !servletPath.endsWith(Constants.SUFFIX_JSON)) {
            // 获取 Session
            Session session = subject.getSession();
            // 获取登录用户
            LoginUser loginUser = (LoginUser) session.getAttribute(Constants.LOGIN_USER);
            // 菜单 ID 和父 ID Map
            Map<String, Long> menuIdAndParentIds = Constants.USER_MENU_URL_CACHE.get(servletPath);

            // 如果是首页请求或存在其他普通请求的菜单 ID
            if (Constants.URL_INDEX.equals(servletPath) || (menuIdAndParentIds != null)) {
                // 菜单 ID
                long menuId = Constants.VALUE_L_0;
                // 菜单父 ID
                long menuParentId = Constants.VALUE_L_0;

                if (menuIdAndParentIds != null) {
                    menuId = menuIdAndParentIds.get(Constants.MENU_ID);
                    menuParentId = menuIdAndParentIds.get(Constants.MENU_PARENT_ID);
                }

                session.setAttribute(Constants.MENU_ID, menuId);
                session.setAttribute(Constants.MENU_PARENT_ID, menuParentId);

                log.debug("账号：{}，菜单 ID：{}，菜单父 ID：{}--->已存入 Session 中", loginUser.getLoginid(), menuId, menuParentId);
            }
        }

        chain.doFilter(request, response);
    }
}